<?php
if (!defined('_PS_VERSION_'))
	exit;

class PeProducTabs extends Module
{
  function __construct()
	{
		$this->name = 'peproductabs';
		$this->tab = 'front_office_features';
		$this->version = 1.1;
		$this->author = 'PrestaExt.com';
		$this->need_instance = 0;

		parent::__construct();

		$this->displayName = $this->l('PE Smart Tabs Free');
		$this->description = $this->l('PE Smart Tabs Free');
	}
	
	public function install() {
		Configuration::updateValue('PE_TABS_NUMBER', 15);
		Configuration::updateValue('PE_TABS_NUM_COLUMN', 4);
		Configuration::updateValue('PE_TABS_NUM_ROW', 1);
		Configuration::updateValue('PE_TABS_WIDTH', 700);
		Configuration::updateValue('PE_TABS_HEIGHT', 320);
		Configuration::updateValue('PE_TABS_THUMB_WIDTH', 160);
		Configuration::updateValue('PE_TABS_THUMB_HEIGHT', 160);
		Configuration::updateValue('PE_TABS_SHOWLINK', 1);
		Configuration::updateValue('PE_TABS_TITLE', 1);
		Configuration::updateValue('PE_TABS_LINKTITLE', 1);
		Configuration::updateValue('PE_TABS_DESC', 1);
		Configuration::updateValue('PE_TABS_PRICE', 1);
		Configuration::updateValue('PE_TABS_POSITION', 'top');
		Configuration::updateValue('PE_TABS_LI_WIDTH', 160);
		Configuration::updateValue('PE_TABS_WORDNUMB', 50);	
		
		Configuration::updateValue('PE_TABS_COLOR_BG', '#003854');	
		Configuration::updateValue('PE_TABS_COLOR_BG_ACT', '#006699');	
		Configuration::updateValue('PE_TABS_COLOR_BORD', '#006699');	
		Configuration::updateValue('PE_TABS_COLOR_TEXT', '#FFFFFF');	
		Configuration::updateValue('PE_TABS_BORD_IMG', '#87A7E6');	
		Configuration::updateValue('PE_TABS_COLOR_TILTE', '#595A5E');	
		Configuration::updateValue('PE_TABS_COLOR_DESC', '#595A5E');	
		Configuration::updateValue('PE_TABS_COLOR_PRICE', '#595A5E');
		//Configuration::updateValue('PE_TABS_FONT_TITLE', 'BebasRegular');		
		//Configuration::updateValue('PE_TABS_FONT_PRICE', 'BebasRegular');
		Configuration::updateValue('PE_TABS_FONT_TITLE', 'Arial');
		Configuration::updateValue('PE_TABS_FONT_PRICE', 'Arial');
		
		if (parent::install() == false || 
				$this->registerHook('home') == false || 
				$this->registerHook('header') == false)
			return false;
		return true;
	}
	
	public function uninstall() {
		Configuration::deleteByName('PE_TABS_NUMBER');
		Configuration::deleteByName('PE_TABS_NUM_COLUMN');
		Configuration::deleteByName('PE_TABS_NUM_ROW');
		Configuration::deleteByName('PE_TABS_WIDTH');
		Configuration::deleteByName('PE_TABS_HEIGHT');
		Configuration::deleteByName('PE_TABS_THUMB_WIDTH');
		Configuration::deleteByName('PE_TABS_THUMB_HEIGHT');
		Configuration::deleteByName('PE_TABS_SHOWLINK');
		Configuration::deleteByName('PE_TABS_TITLE');
		Configuration::deleteByName('PE_TABS_LINKTITLE');
		Configuration::deleteByName('PE_TABS_DESC');
		Configuration::deleteByName('PE_TABS_PRICE');
		Configuration::deleteByName('PE_TABS_POSITION');
		Configuration::deleteByName('PE_TABS_LI_WIDTH');
		Configuration::deleteByName('PE_TABS_WORDNUMB');	
		Configuration::deleteByName('PE_TABS_COLOR_BG');	
		Configuration::deleteByName('PE_TABS_COLOR_BG_ACT');	
		Configuration::deleteByName('PE_TABS_COLOR_BORD');	
		Configuration::deleteByName('PE_TABS_COLOR_TEXT');	
		Configuration::deleteByName('PE_TABS_BORD_IMG');	
		Configuration::deleteByName('PE_TABS_COLOR_TILTE');	
		Configuration::deleteByName('PE_TABS_COLOR_DESC');	
		Configuration::deleteByName('PE_TABS_COLOR_PRICE');			
		Configuration::deleteByName('PE_TABS_FONT_TITLE');			
		Configuration::deleteByName('PE_TABS_FONT_DESC');			
		Configuration::deleteByName('PE_TABS_FONT_PRICE');
		Configuration::deleteByName('PE_TABS_LI_NAME');				
		//Configuration::deleteByName('PE_TABS_ADDCART');				
    if(!parent::uninstall())
    	return false;
    return true;
  }
	
	public function getContent()
	{
		$output = '<h2>'.$this->displayName.'</h2>';
		if (Tools::isSubmit('submitProducTabs')) 	{
			$tabsName = Tools::getValue('petabsname');	
			Configuration::updateValue('PE_TABS_LI_NAME', implode(',', $tabsName));	
			//Configuration::updateValue('PE_TABS_ADDCART', Tools::getValue('show_addcart'));	

			$output .= '<div class="conf confirm"><img src="../img/admin/ok.gif" alt="'.$this->l('Confirmation').'" />'.$this->l('Settings updated').'</div>';
		}
		$html .= '
			<div class="intro">
				<p>If you have any problem, email us at <a href="mailto:support@prestaext.com"><b>support@prestaext.com</b></a>
				You can visit here <a href="http://prestaext.com"><b>www.PrestaExt.com</b></a> for more modules. </p>
			</div>
			<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post">
				<table id="penivoimageadmin" width="100%" cellpadding="2" cellspacing="1" >
					<tr>
						<td width="100%" valign="top">'.$this->formSetting().'</td>				
					</tr>
					<tr>
						<td><input type="submit" name="submitProducTabs" value="'.$this->l('Save').'" class="button" style="cursor: pointer"/></td>
					</tr>
				</table>
			</form>
		';
		return $output.$html;
	}
	
	public function formSetting() {
		$html = '
			<fieldset>
				<legend><img src="'.$this->_path.'logo.gif" alt="" title="" />'.$this->l('Themes option').'</legend>
				<label>'.$this->l('Select tabs index').'</label>
				<div class="margin-form">
			';
			$tabNames = Configuration::get('PE_TABS_LI_NAME');
			$tabNames = explode(',', $tabNames);
		$html .= '<select name="petabsname[]" multiple="true" style="width: 195px; height:100px">					
						<option value="1" '.(in_array('1', $tabNames, true) ? 'selected="selected"' : '' ).'>'.$this->l(' New Products ').'</option>
						<option value="2" '.(in_array('2', $tabNames, true) ? 'selected="selected"' : '' ).'>'.$this->l('Special Products').'</option>
						<option value="3" '.(in_array('3', $tabNames, true) ? 'selected="selected"' : '' ).'>'.$this->l('Feature Products').'</option>
						<option value="4" '.(in_array('4', $tabNames, true) ? 'selected="selected"' : '' ).'>'.$this->l('Top Sellers').'</option>
					</select>		
				</div>
			</fieldset>
		';
		
		return $html;
	}

	function hookHome($params) {
		global $smarty;
		$productNum = Configuration::get('PE_TABS_NUMBER');
		$pColumn = Configuration::get('PE_TABS_NUM_COLUMN');
		$pNumRow = Configuration::get('PE_TABS_NUM_ROW');
		$width = Configuration::get('PE_TABS_WIDTH');
		if (Configuration::get('PE_TABS_POSITION') == 'left' || Configuration::get('PE_TABS_POSITION') == 'right') {
			$fullWidth = $width;
			$width = $width-Configuration::get('PE_TABS_LI_WIDTH')-4;			
		}
		$thumb_width = Configuration::get('PE_TABS_THUMB_WIDTH');

		if ($pNumRow) {
			$widthItem = ceil(($width - 20)/$pColumn)-5;
		}

		$widthLi = $width-20;		
		if (isset($fullWidth)) $smarty->assign('fullWidth', $fullWidth);
		$smarty->assign('width_li', $widthLi);
		$smarty->assign('width_li_tabs', Configuration::get('PE_TABS_LI_WIDTH'));
		$smarty->assign('width_item', $widthItem);			
		$smarty->assign('width', $width);
		
		$tabNames = Configuration::get('PE_TABS_LI_NAME');		
		$tabNames = explode(',', $tabNames);
		$smarty->assign('tabNames', $tabNames);
		
		$smarty->assign('num_column', Configuration::get('PE_TABS_NUM_COLUMN'));
		$smarty->assign('num_row', Configuration::get('PE_TABS_NUM_ROW'));
		$smarty->assign('img_showlink', Configuration::get('PE_TABS_SHOWLINK'));
		$smarty->assign('show_title', Configuration::get('PE_TABS_TITLE'));
		$smarty->assign('title_showlink', Configuration::get('PE_TABS_LINKTITLE'));
		$smarty->assign('show_desc', Configuration::get('PE_TABS_DESC'));
		$smarty->assign('show_price', Configuration::get('PE_TABS_PRICE'));
		$smarty->assign('show_addcart', Configuration::get('PE_TABS_ADDCART'));
		$smarty->assign('num_word', Configuration::get('PE_TABS_WORDNUMB'));
		$smarty->assign('productNum', $productNum);
		//$smarty->assign('static_token', Tools::getToken(false));
		
		$baseDir = $smarty->tpl_vars;
		$baseDir = $baseDir['base_dir']->value;
		
		$newProducts = $this->_getNewProducts((int)$params['cookie']->id_lang, $baseDir);
		$smarty->assign('newproducts', $newProducts);

		$specialProduct = $this->_getSpecial((int)$params['cookie']->id_lang);
		$smarty->assign('specialProduct', $specialProduct);

		$bestSellers = $this->bestSellers($params);
		$smarty->assign('bestSellers', $bestSellers);
	
		$featureProducts = $this->_getFeature((int)$params['cookie']->id_lang);
		$smarty->assign('featureProduct', $featureProducts);	
		if (Configuration::get('PE_TABS_POSITION') == 'top') {
			return $this->display(__FILE__, 'peproductabs_top.tpl');
		}
	}
	
	public function hookHeader() {
		$this->context->controller->addCSS(($this->_path).'font/fontfamily.css', 'all');
		$this->context->controller->addCSS(($this->_path).'css/style_top.css', 'all');
		$this->context->controller->addJS(($this->_path).'js/jquery.carouFredSel-5.6.4-packed.js');
		//$this->context->controller->addJS(($this->_path).'js/jquery.carouFredSel-6.1.0-packed.js');
		
		$js = '
			<script charset="utf-8" type="text/javascript">
				/*
				$(function () {
				
					var tabContainers = $("div#pe-productabs > div");
					tabContainers.hide().filter(":first").show();
					
					$("div#pe-productabs ul.tabs a").click(function () {
						tabContainers.hide();
						tabContainers.filter(this.hash).show();
						$("div#pe-productabs ul.tabs a").removeClass("selected");
						$(this).addClass("selected");
						return false;
					}).filter(":first").click();
				});*/
			</script>
		';

		$pColumn = Configuration::get('PE_TABS_NUM_COLUMN');
		$pNumRow = Configuration::get('PE_TABS_NUM_ROW');
		$width = Configuration::get('PE_TABS_WIDTH');
		$height = Configuration::get('PE_TABS_HEIGHT');
		$thumb_width = Configuration::get('PE_TABS_THUMB_WIDTH');
		if ($pNumRow) {
			$widthItem = ceil(($width - 20)/$pColumn)-5;
		}
		$widthLi = $width-20;	
		
		$addCss = '
			<style type="text/css">
				ul.tabs li a {
					background: '.Configuration::get('PE_TABS_COLOR_BG').';
					color: '.Configuration::get('PE_TABS_COLOR_TEXT').';
				}
				ul.tabs li a.selected {
					background: '.Configuration::get('PE_TABS_COLOR_BG_ACT').';
				}
				.pagination a span,
				.petabscontent {
					border: 1px solid '.Configuration::get('PE_TABS_COLOR_BORD').';
				}
				.pe-element .image {
					border: 1px solid '.Configuration::get('PE_TABS_BORD_IMG').';
				}
				.pe-element .title {
					color: '.Configuration::get('PE_TABS_COLOR_TILTE').';
				}
				.pe-element .desc {
					color: '.Configuration::get('PE_TABS_COLOR_DESC').';
				}
				.pe-element .s_price {
					color: '.Configuration::get('PE_TABS_COLOR_PRICE').';
				}
				.product_wrap_slider {
					min-height: '.$height.'px;
				}
				.inner-content {
					width: '.$widthLi.'px;
				}
				.pe-element .image {
				width: '.($widthItem-2).'px 
				}	
				#pe-productabs .petabs-clip {
					width: '.($width - 20).'px;
				}			
				.pagination a.selected span {
					background: '.Configuration::get('PE_TABS_COLOR_BORD').';
				}
				#pe-productabs .pe-element .title {
					font-family: \''.Configuration::get('PE_TABS_FONT_TITLE').'\';
				} 
				#pe-productabs .pe-element .desc {
					font-family: \''.Configuration::get('PE_TABS_FONT_DESC').'\';
				} 
				#pe-productabs .pe-element .s_price {
					font-family: \''.Configuration::get('PE_TABS_FONT_PRICE').'\';
				} 
				#pe-productabs .pagination {
				text-align: right;
				margin-right: 5px;
			}	
		';
		$addCss .='</style>';
		
		return $addCss.$js;
	}
	
	public function wordLimit($str, $limit = 100, $end_char = '&#8230;') {
		if (trim($str) == '') return $str;
		
		// always strip tags for text
		$str = strip_tags($str);

		$find = array("/\r|\n/","/\t/","/\s\s+/");
		$replace = array(" "," "," ");
		$str = preg_replace($find,$replace,$str);
		
		preg_match('/\s*(?:\S*\s*){'.(int) $limit.'}/', $str, $matches);
		if (strlen($matches[0]) == strlen($str))
				$end_char = '';
		return rtrim($matches[0]).$end_char;
	}
	
	public function _getNewProducts($id_lang, $baseDir) {
		global $smarty;
		
		//$newProducts = Product::getNewProducts((int)($id_lang), 0);// (int)(Configuration::get('PE_TABS_NUMBER')));	
		
		$categoryId = 20;
		$category = New Category($categoryId);
		$products = $category->getProducts((int)($this->context->language->id), 1, 10);
		if (!empty($products))
		foreach ($products as &$item) {
			$item['link_image'] = 'modules/peproductabs/timthumb.php?src='.$this->context->link->getImageLink($item['link_rewrite'], $item['id_image']).'&w='.Configuration::get('PE_TABS_THUMB_WIDTH').'&h='.Configuration::get('PE_TABS_THUMB_HEIGHT').'';	
			$item['static_token'] = Tools::getToken(false);
			if ($item['description_short']) {
				$item['desc'] = $this->wordLimit($item['description_short'], Configuration::get('PE_TABS_WORDNUMB'));
			}
			else $item['desc'] = $this->wordLimit($item['description'], Configuration::get('PE_TABS_WORDNUMB'));
		}

		return $products;
	}
	
	public function _getSpecial($id_lang, $beginning = false, $ending = false) {
		/*
		$currentDate = date('Y-m-d H:i:s');
		$ids_product = self::_getProductIdByDate((!$beginning ? $currentDate : $beginning), (!$ending ? $currentDate : $ending));

		$groups = FrontController::getCurrentCustomerGroups();
		$sqlGroups = (count($groups) ? 'IN ('.implode(',', $groups).')' : '= 1');

		// Please keep 2 distinct queries because RAND() is an awful way to achieve this result
		$sql = '
		SELECT p.id_product
		FROM `'._DB_PREFIX_.'product` p
		WHERE 1
		AND p.`active` = 1
		AND p.`id_product` IN ('.implode(', ', $ids_product).')
		AND p.`id_product` IN (
			SELECT cp.`id_product`
			FROM `'._DB_PREFIX_.'category_group` cg
			LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
			WHERE cg.`id_group` '.$sqlGroups.'
		)
		ORDER BY RAND()';
		$id_products = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
	
		if (!$id_products) {
			return false;
		}
		$where = '';
		foreach ($id_products as $index => $id) {
			if ($index == 0) $where = 'p.id_product = '.$id['id_product'];
			else $where .= ' OR p.id_product = '.$id['id_product'];
		}
		
		$query = '
		SELECT DISTINCT p.id_product, p.*, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, p.`ean13`,  p.`upc`,
			i.`id_image`, il.`legend`, t.`rate`
		FROM `'._DB_PREFIX_.'product` p
		LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
		LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)($id_lang).')
		LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
													AND tr.`id_country` = '.(int)Country::getDefaultCountryId().'
													AND tr.`id_state` = 0)
		LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`)
		WHERE p.`active` = 1 AND ('.$where.')';	
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($query);

		foreach ($result as &$item) {
			$item = Product::getProductProperties($id_lang, $item);
			$item['link_image'] ='modules/peproductabs/timthumb.php?src='.$this->context->link->getImageLink($item['link_rewrite'], $item['id_image']).'&w='.Configuration::get('PE_TABS_THUMB_WIDTH').'&h='.Configuration::get('PE_TABS_THUMB_HEIGHT').'';
			$item['static_token'] = Tools::getToken(false);
			if ($item['description_short']) {
				$item['desc'] = $this->wordLimit($item['description_short'], Configuration::get('PE_TABS_WORDNUMB'));
			}
			else $item['desc'] = $this->wordLimit($item['description'], Configuration::get('PE_TABS_WORDNUMB'));
		}

		return $result;
		*/
		$categoryId = 23;
		$category = New Category($categoryId);
		$products = $category->getProducts((int)($this->context->language->id), 1, 10);
		if (!empty($products))
		foreach ($products as &$item) {
			$item['link_image'] = 'modules/peproductabs/timthumb.php?src='.$this->context->link->getImageLink($item['link_rewrite'], $item['id_image']).'&w='.Configuration::get('PE_TABS_THUMB_WIDTH').'&h='.Configuration::get('PE_TABS_THUMB_HEIGHT').'';	
			$item['static_token'] = Tools::getToken(false);
			if ($item['description_short']) {
				$item['desc'] = $this->wordLimit($item['description_short'], Configuration::get('PE_TABS_WORDNUMB'));
			}
			else $item['desc'] = $this->wordLimit($item['description'], Configuration::get('PE_TABS_WORDNUMB'));
		}

		return $products;
	}
	
	static protected function _getProductIdByDate($beginning, $ending) {
		global $cookie, $cart;

		$id_group = $cookie->id_customer ? (int)(Customer::getDefaultGroupId((int)($cookie->id_customer))) : _PS_DEFAULT_CUSTOMER_GROUP_;
		$id_address = $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
		$ids = Address::getCountryAndState($id_address);
		$id_country = (int)($ids['id_country'] ? $ids['id_country'] : Configuration::get('PS_COUNTRY_DEFAULT'));
		return SpecificPrice::getProductIdByDate((int)(Shop::getCurrentShop()), (int)($cookie->id_currency), $id_country, $id_group, $beginning, $ending);
	}
	
	public function _getFeature($id_lang) {		
		/*
		$category = new Category(Context::getContext()->shop->getCategory(), $id_lang);
		$nb = (int)(Configuration::get('PE_TABS_NUMBER'));
		$products = $category->getProducts((int)$id_lang, 1, ($nb ? $nb : 10));
		
		
		foreach ($products as &$item) {
			$item['link_image'] = 'modules/peproductabs/timthumb.php?src='.$this->context->link->getImageLink($item['link_rewrite'], $item['id_image']).'&w='.Configuration::get('PE_TABS_THUMB_WIDTH').'&h='.Configuration::get('PE_TABS_THUMB_HEIGHT').'';
			$item['static_token'] = Tools::getToken(false);
			if ($item['description_short']) {
				$item['desc'] = $this->wordLimit($item['description_short'], Configuration::get('PE_TABS_WORDNUMB'));
			}
			else $item['desc'] = $this->wordLimit($item['description'], Configuration::get('PE_TABS_WORDNUMB'));
		}

		return $products;
		*/
		$categoryId = 21;
		$category = New Category($categoryId);
		$products = $category->getProducts((int)($this->context->language->id), 1, 10);
		if (!empty($products))
		foreach ($products as &$item) {
			$item['link_image'] = 'modules/peproductabs/timthumb.php?src='.$this->context->link->getImageLink($item['link_rewrite'], $item['id_image']).'&w='.Configuration::get('PE_TABS_THUMB_WIDTH').'&h='.Configuration::get('PE_TABS_THUMB_HEIGHT').'';	
			$item['static_token'] = Tools::getToken(false);
			if ($item['description_short']) {
				$item['desc'] = $this->wordLimit($item['description_short'], Configuration::get('PE_TABS_WORDNUMB'));
			}
			else $item['desc'] = $this->wordLimit($item['description'], Configuration::get('PE_TABS_WORDNUMB'));
		}

		return $products;
	}
	
	public function bestSellers($params) {	
		/*
		$currency = new Currency($params['cookie']->id_currency);
		$bestsellers = ProductSale::getBestSalesLight((int)($params['cookie']->id_lang), 0, (int)(Configuration::get('PE_TABS_NUMBER')));

		if (!$bestsellers)
			return;
		$best_sellers = array();

		if ($bestsellers) {
			foreach ($bestsellers as $bestseller)
			{
				$bestseller['price'] = Tools::displayPrice(Product::getPriceStatic((int)($bestseller['id_product'])), $currency);
				$bestseller['link_image'] = 'modules/peproductabs/timthumb.php?src='.$this->context->link->getImageLink($bestseller['link_rewrite'], $bestseller['id_image']).'&w='.Configuration::get('PE_TABS_THUMB_WIDTH').'&h='.Configuration::get('PE_TABS_THUMB_HEIGHT').'';
				$bestseller['static_token'] = Tools::getToken(false);
				if ($bestseller['description_short']) {
					$bestseller['desc'] = $this->wordLimit($bestseller['description_short'], Configuration::get('PE_TABS_WORDNUMB'));
				}
				else $bestseller['desc'] = $this->wordLimit($bestseller['description'], Configuration::get('PE_TABS_WORDNUMB'));
			
				$best_sellers[] = $bestseller;
			}
		}

		return $best_sellers;	
		*/
		$categoryId = 22;
		$category = New Category($categoryId);
		$products = $category->getProducts((int)($this->context->language->id), 1, 10);
		if (!empty($products))
		foreach ($products as &$item) {
			$item['link_image'] = 'modules/peproductabs/timthumb.php?src='.$this->context->link->getImageLink($item['link_rewrite'], $item['id_image']).'&w='.Configuration::get('PE_TABS_THUMB_WIDTH').'&h='.Configuration::get('PE_TABS_THUMB_HEIGHT').'';	
			$item['static_token'] = Tools::getToken(false);
			if ($item['description_short']) {
				$item['desc'] = $this->wordLimit($item['description_short'], Configuration::get('PE_TABS_WORDNUMB'));
			}
			else $item['desc'] = $this->wordLimit($item['description'], Configuration::get('PE_TABS_WORDNUMB'));
		}

		return $products;
	}
}